package cn.yili12.server.websocket.handler;

import cn.yili12.server.client.handler.BaseClientHandler;
import cn.yili12.server.client.vo.ClientMessage;
import cn.yili12.server.client.vo.ClientMessageType;
import cn.yili12.server.websocket.NioWebSocketChannelPool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * TextWebSocketFrame 类型，表示一个文本帧(frame)
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class WebSocketContentHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    private NioWebSocketChannelPool webSocketChannelPool;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("服務器收到消息" + msg.text());
        try {
            JSONObject jsonObject = JSON.parseObject(msg.text());
            ClientMessage clientMessage = JSON.toJavaObject(jsonObject, ClientMessage.class);
            ClientMessageType type = clientMessage.getType();
            BaseClientHandler baseHandler = (BaseClientHandler) applicationContext.getBean(type.getHandler());
            baseHandler.handler(clientMessage, ctx.channel());
        } catch (Exception e) {
            log.error("解析客服端报文失败", e);
        }
        //回复客户端
//        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + LocalDateTime.now() + "   " + msg.text()));
    }

    //当web客户端连接后
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //id 表示唯一的值 LongText
        log.debug("handlerAdded 被调用 " + ctx.channel().id().asLongText());
        webSocketChannelPool.addChannel(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.debug("handlerRemoved 被调用 " + ctx.channel().id().asLongText());
        webSocketChannelPool.removeChannel(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.debug("exceptionCaught 被调用 " + ctx.channel().id().asLongText());
        webSocketChannelPool.removeChannel(ctx.channel());
    }


}
